package com.gitee.zhuyb.interceptor;

import com.gitee.zhuyb.domain.PageUtil;
import com.gitee.zhuyb.domain.PageVo;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;

import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @version 1.0.0
 * @Description: #结果集拦截器
 * @Date: 2021/10/30 14:57
 * @Copyright (C) ZhuYouBin
 */
@Intercepts({@Signature(args = { Statement.class }, method = "handleResultSets", type = ResultSetHandler.class)})
public class ResultInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        List result = new ArrayList();
        // 获取PageVo对象
        PageVo pageVo = PageUtil.getPageVo();
        if (pageVo != null) {
            List<?> list = (List<?>) invocation.proceed();
            // 将查询结果设置到PageVo对象中
            pageVo.setData(list);
            result.add(pageVo);
        } else {
            result = (List)invocation.proceed();
        }
        return result;
    }

    @Override
    public Object plugin(Object target) {
        if(target instanceof ResultSetHandler){
            return Plugin.wrap(target, this);
        }else{
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
